// subpages/pages/cancelNFCBind/cancelNFCBind.js
//获取应用实例
var util = require('../../utils/util.js')
const app = getApp()
let movedistance = 0;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        success: 0,
        haveVote: 0,
        showResult: 0,
        loading: 1,
        itemArr: [],
        Alldata: null,
        formName: '',
        formKey: '',
        selectValue: '',
        message: "",
        animationList: []
    },
    //跳转主页面
    backhome: function (e) {
        wx.switchTab({
            url: '/pages/index/index'
        })
    },

    reset: function (e) {
        this.setData({
            haveQuestion: 1,
            haveRecord: 0,
            haveStorage: 0
        })
    },

    continue: function (e) {
        let current = this.data.storage.current || (this.data.storage.progressNum - 1)
        this.setData({
            current: current,
            haveQuestion: 1,
            haveRecord: 0,
            haveStorage: 0,
            itemArr: this.data.storage.itemArr,
            progressPercent: this.data.storage.progressNum / this.data.storage.itemArr.length * 100
        })
    },

    nextPage: function (e) {
        let animationList = this.data.animationList.slice()
        let animation = wx.createAnimation({
            duration: 400,
            timingFunction: 'ease'
        });
        animation.translateX(-wx.getSystemInfoSync().windowWidth).step()
        animationList[this.data.current] = animation.export()
        animationList[this.data.current + 1] = animation.export()
        this.setData({
            animationList: animationList
        })
        setTimeout(function () {
            this.setData({
                current: this.data.current + 1
            })
        }.bind(this), 430);
    },

    prePage: function (e) {
        let animationList = this.data.animationList.slice()
        let animation = wx.createAnimation({
            duration: 400,
            timingFunction: 'ease'
        });
        animation.translateX(wx.getSystemInfoSync().windowWidth).step()
        animationList[this.data.current] = animation.export()
        animationList[this.data.current - 1] = animation.export()
        this.setData({
            animationList: animationList
        })
        setTimeout(function () {
            this.setData({
                current: this.data.current - 1
            })
        }.bind(this), 430);
    },

    update: function (e) {
        let itemArr = this.data.itemArr
        let record = this.data.record.data
        for (let i in itemArr) {
            if (i == "progressNum") continue;
            let type = itemArr[i].type
            let content = record[i].content
            itemArr[i].progress = true
            if (type == "input" || type == "textarea")
                itemArr[i].preValue = content
            else if (type == "select")
                itemArr[i].preValue = content
            else if (type == "datePicker")
                itemArr[i].Time = content
            else if (type == "dateRangePicker") {
                itemArr[i].startTime = content[0]
                itemArr[i].endTime = content[1]
            } else if (type == "radio") {
                for (let j in itemArr[i].props.options) {
                    itemArr[i].props.options[j].checked = itemArr[i].props.options[j].label === content
                }
            } else if (type == "checkbox") {
                for (let j in itemArr[i].props.options) {
                    itemArr[i].props.options[j].checked = content.includes(itemArr[i].props.options[j].label)
                }
            }
        }
        itemArr.progressNum = itemArr.length
        this.setData({
            haveQuestion: 1,
            haveRecord: 0,
            itemArr: itemArr,
            progressPercent: 100
        })
    },

    sort: function (e) {
        let idx = e.currentTarget.dataset.idx
        let type = e.currentTarget.dataset.type
        let listData = this.data.listData
        if (type == "num"){
            if (listData[idx].numSort == "desc"){
                listData[idx].options.sort(function(a , b){return a.num-b.num})
                listData[idx].numSort = "asc"
            }
            else {
                listData[idx].options.sort(function(a , b){return b.num-a.num})
                listData[idx].numSort = "desc"
            }
        }
        else {
            if (listData[idx].labelSort == "asc"){
                listData[idx].options.sort(function(a , b){return b.label.localeCompare(a.label,'zh-CN')})
                listData[idx].labelSort = "desc"
            }
            else {
                listData[idx].options.sort(function(a , b){return a.label.localeCompare(b.label,'zh-CN')})
                listData[idx].labelSort = "asc"
            }
        }
        this.setData({
            listData: listData
        })
    },

    result: function (e) {
        wx.request({
            url: app.questionnaireUrl + '/recordFormal/statisticalAnswer',
            method: 'GET',
            data: {
                formKey: this.data.formKey
            },
            dataType: 'json',
            success: res => {
                let listData = res.data
                listData.forEach(item => {
                    item.options.forEach(option => {
                        option.percent = (option.num / item.memberNum *100).toFixed(0)
                    });
                });
                this.setData({
                    showResult:1,
                    listData: listData
                })
            }
        })
    },

    onReady: function () {
        this.animation = wx.createAnimation({
            delay: 0,
            duration: 300,
            transformOrigin: 'left top 0',
            timingFunction: 'ease',
        })
    },

    touchstartX: function (e) {
        // 获取触摸X坐标
        this.recordX = e.touches[0].clientX;
    },

    touchendX(e) {
        let idx = e.currentTarget.dataset.idx
        let endX = e.changedTouches[0].clientX
        let move = endX - this.recordX
        let progress = this.data.itemArr[idx].progress || false

        if (move < -10) {
            if (progress)
                this.nextPage()
        } else if (move > 10) {
            if (idx > 0)
                this.prePage()
        }
    },

    close: function () {
        this.animation.translateY(-(wx.getSystemInfoSync().screenHeight)).step()
        this.setData({
            animation: this.animation.export(),
            scroll: true
        })
    },

    touchstartY: function (e) {
        // 获取触摸Y坐标
        this.recordY = e.touches[0].clientY;
    },

    touchmoveY(e) {
        let currentY = e.touches[0].clientY;
        movedistance = currentY - this.recordY; // 获取移动距离
        if (movedistance <= 0)
            this.slideAnimation(movedistance);
    },

    touchendY() {
        let recordY;
        if (movedistance >= -50 && movedistance <= 0) { // 移动达到距离就动画显示全部操作项
            recordY = 0;
            this.slideAnimation(recordY);
        } else if (movedistance <= -50) { // 移动未达到距离即还原
            this.close();
        }
    },

    slideAnimation(recordY) {
        let animation = wx.createAnimation({
            duration: 0,
            timingFunction: 'ease'
        });
        animation.translateY(recordY + 'px', 0).step()
        this.setData({
            animation: animation.export()
        })
    },

    onLoad: function (options) {
        this.setData({
            success: 0
        })
        wx.request({
            url: app.questionnaireUrl + '/questionnaireFormal/getReleaseThemeByDepartment',
            method: 'GET',
            data: {
                schoolId: app.globalData.departmentId,
                displayType: 1
            },
            dataType: 'json',
            success: res => {
                console.log("release theme", res)
                if (res.data.data == null || res.data.data == "") {
                    this.setData({
                        haveQuestion: 0,
                        message: "暂无已发布问卷"
                    })
                } else {
                    wx.request({
                        url: app.questionnaireUrl + '/itemFormal/queryItems',
                        method: 'GET',
                        data: {
                            formKey: res.data.data.formKey
                        },
                        dataType: 'json',
                        success: res1 => {
                            let Alldata = res1.data.data
                            console.log(res1.data.data)
                            Alldata.progressNum = 0
                            for (let i = 0; i < Alldata.length; i++) {
                                if (Alldata[i].formItemProps.label.indexOf("姓名") >= 0) {
                                    Alldata[i].preValue = app.globalData.realname;
                                    Alldata[i].progress = true
                                    Alldata.progressNum++
                                }
                                if (Alldata[i].formItemProps.label.indexOf("电话") >= 0 || Alldata[i].formItemProps.label.indexOf("手机") >= 0 || Alldata[i].formItemProps.label.indexOf("联系方式") >= 0) {
                                    Alldata[i].preValue = app.globalData.phone;
                                    Alldata[i].progress = true
                                    Alldata.progressNum++
                                }
                                if (Alldata[i].formItemProps.label.indexOf("学校") >= 0) {
                                    Alldata[i].preValue = app.globalData.department;
                                    Alldata[i].progress = true
                                    Alldata.progressNum++
                                }
                                if (Alldata[i].formItemProps.label.indexOf("任职") >= 0) {
                                    Alldata[i].preValue = app.globalData.identity;
                                    Alldata[i].progress = true
                                    Alldata.progressNum++
                                }
                            }
                            if (res.data.data.contentType == 1) {
                                this.setData({
                                    scroll: true,
                                    itemArr: Alldata,
                                    progressPercent: Alldata.progressNum / Alldata.length * 100
                                })
                            } else if(res.data.data.contentType == 2) {
                                setTimeout(function () {
                                    this.setData({
                                        itemArr: Alldata,
                                        current: 0,
                                        size: Alldata.length,
                                    })
                                }.bind(this), 400);
                            } else {
                                this.setData({
                                    scroll: true,
                                    itemArr: Alldata,
                                    progressPercent: Alldata.progressNum / Alldata.length * 100
                                })
                            }
                        },
                    });
                    this.setData({
                        formKey: res.data.data.formKey,
                        formName: res.data.data.name,
                        formDescription: res.data.data.description != "" ? res.data.data.description + "\n\n" : res.data.data.description,
                        contentType: res.data.data.contentType
                    })
                    // 这里请求数据库查询填写记录
                    wx.request({
                        url: app.questionnaireUrl + '/recordFormal/queryRecord',
                        method: 'POST',
                        data: {
                            formKey: res.data.data.formKey,
                            userId: app.globalData.userId
                        },
                        dataType: 'json',
                        success: res2 => {
                            if (res2.data == null || res2.data == "") {
                                let storage = wx.getStorageSync(this.data.formKey.toString()) || null
                                if (storage != null) {
                                    for (let i in storage.itemArr) {
                                        let empty = storage.itemArr[i].empty
                                        if (empty != false) {
                                            storage.current = parseInt(i)
                                            break;
                                        }
                                    }
                                    storage.itemArr.progressNum = storage.progressNum
                                    let progressPercent = (storage.progressNum / storage.itemArr.length * 100).toFixed(0)
                                    this.setData({
                                        storage: storage,
                                        haveStorage: 1,
                                        message: "之前的填写进度为" + progressPercent + "%" + "\n是否继续上次填写？"
                                    })
                                } else {
                                    this.setData({
                                        haveQuestion: 1,
                                        haveRecord: 0
                                    })

                                }
                            } else {
                                if (this.data.contentType == 1) {
                                    this.setData({
                                        haveRecord: 1,
                                        message: "您已经回答过此问卷",
                                        record: res2.data
                                    })
                                } else if (this.data.contentType == 2) {
                                    setTimeout(function () {
                                        this.setData({
                                            success: 1,
                                        })
                                    }.bind(this), 10);
                                    this.setData({
                                        message: "您已经完成此试卷"
                                    })
                                } else{
                                    setTimeout(function () {
                                        this.setData({
                                            haveVote: 1,
                                        })
                                    }.bind(this), 10);
                                    this.setData({
                                        message: "您已经完成此投票"
                                    })
                                }
                            }
                        }
                    })
                }
            },
            fail: (res) => {
                wx.showToast({
                    title: '网络异常！',
                    image: '/images/warning.png'
                })
            },
            complete: () => {
                this.setData({
                    loading: 0
                })
            }
        });
    },

    valueChange: function (e) {
        let current = e.currentTarget.dataset.current
        let itemArr = this.data.itemArr
        let type = itemArr[current].type
        if (itemArr[current].progress != true && type != 'dateRangePicker') {
            itemArr[current].progress = true
            itemArr.progressNum++
        }

        if (type == "input" || type == "textarea") {
            itemArr[current].preValue = e.detail.value
            if (e.detail.value != "") {
                itemArr[current].empty = false
            } else {
                itemArr[current].progress = false
                itemArr.progressNum--
            }
        } else if (type == "radio") {
            itemArr[current].preValue = e.detail.value
            let options = itemArr[current].props.options
            let answer = e.detail.value
            for (let i in itemArr[current].props.options) {
                options[i].checked = options[i].label === answer
            }
            if (e.detail.value != "") {
                itemArr[current].empty = false
            }
        } else if (type == "checkbox") {
            itemArr[current].preValue = e.detail.value
            let options = itemArr[current].props.options
            let value = []
            for (let i in e.detail.value) {
                value.push(e.detail.value[i])
            }
            for (let i in itemArr[current].props.options) {
                options[i].checked = value.includes(options[i].label)
            }
            if (e.detail.value != "") {
                itemArr[current].empty = false
            } else {
                itemArr[current].progress = false
                itemArr.progressNum--
            }
        } else if (type == "datePicker") {
            itemArr[current].Time = e.detail.value
            if (e.detail.value != "") {
                itemArr[current].empty = false
            }
        } else if (type == "dateRangePicker") {
            let name = e.currentTarget.dataset.name
            if (name == "start")
                itemArr[current].startTime = e.detail.value
            else if (name == "end")
                itemArr[current].endTime = e.detail.value
            if (itemArr[current].startTime != null && itemArr[current].endTime != null) {
                itemArr[current].empty = false
                if (itemArr[current].progress != true) {
                    itemArr[current].progress = true
                    itemArr.progressNum++
                }
            }
        } else if (type == "select") {
            this.setData({
                selectValue: e.detail.label
            })
            itemArr[current].preValue = e.detail.label
            if (e.detail.label != "") {
                itemArr[current].empty = false
            }
        }
        wx.setStorage({
            key: this.data.formKey.toString(),
            data: {
                "itemArr": itemArr,
                "progressNum": itemArr.progressNum
            }
        })
        this.setData({
            itemArr: itemArr,
            progressPercent: itemArr.progressNum / itemArr.length * 100
        })
    },
    
    formSubmit: util.throttle(function (e) {
        console.log("input form value", e.detail.value);
        let Info = [];
        let scrollTo = 0;
        let flag = 0;
        let score = 0;
        let vals = e.detail.value;
        let itemArr = this.data.itemArr
        console.log(itemArr)

        for (let i in itemArr) {
            if (i == "progressNum") continue;
            console.log(itemArr[i])
            let type = itemArr[i].type;
            let title = itemArr[i].formItemProps.label;
            let required = itemArr[i].formItemProps.required
            let answer = itemArr[i].formItemProps.answer || {}
            let preScore = 0

            if (required == true) {
                if (type == "dateRangePicker") {
                    if (vals[title + " start"] == null || vals[title + " end"] == null) {
                        flag = 1
                        scrollTo = itemArr[i].sort
                        itemArr[i].empty = true
                        break;
                    }
                } else {
                    if (vals[title] == "" || vals[title] == null) {
                        flag = 1
                        scrollTo = itemArr[i].sort
                        itemArr[i].empty = true
                        break;
                    }
                }
            }

            if (flag == 1) break;

            if (type == "input" || type == "textarea") {
                if (vals[title] == answer.value) {
                    preScore = answer.score
                }
                Info.push({
                    title: title,
                    content: vals[title],
                    score: preScore
                })
            } else if (type == "radio") {
                for (let j in answer) {
                    if (answer[j].label == vals[title]) {
                        preScore = answer[j].score;
                        break;
                    }
                }
                Info.push({
                    title: title,
                    content: vals[title],
                    score: preScore
                })
            } else if (type == "checkbox") {
                let correctAnswer = []
                let correctScore = []
                for (let j in answer) {
                    if (answer[j].score != 0) {
                        correctAnswer.push(answer[j].label)
                        correctScore.push(answer[j].score)
                    }
                }
                for (let j in vals[title]) {
                    if (correctAnswer.indexOf(vals[title][j]) >= 0) {
                        preScore += correctScore[correctAnswer.indexOf(vals[title][j])]
                    } else {
                        preScore = 0;
                        break;
                    }
                }
                Info.push({
                    title: title,
                    content: vals[title],
                    score: parseFloat(preScore.toFixed(1))
                })
            } else if (type == "select") {
                Info.push({
                    title: title,
                    content: vals[title],
                    score: 0
                })
            } else if (type == "datePicker") {
                Info.push({
                    title: title,
                    content: vals[title],
                    score: 0
                })
            } else if (type == "dateRangePicker") {
                let time = []
                time.push(vals[title + " start"])
                time.push(vals[title + " end"])
                Info.push({
                    title: title,
                    content: time,
                    score: 0
                })
            }
            score += preScore;
        }
        console.log("submit data", Info);
        if (flag == 0) {
            wx.request({
                url: app.questionnaireUrl + '/recordFormal/insertOrUpdateRecord',
                method: 'POST',
                data: {
                    formKey: this.data.formKey,
                    data: Info,
                    userId: app.globalData.userId,
                    userName: app.globalData.realname,
                    score: score
                },
                dataType: 'json',
                success: res => {
                    wx.removeStorageSync(this.data.formKey.toString())
                    if(this.data.contentType == 1){
                        this.setData({
                            success: 1,
                            message: "提交成功"
                        })
                    }
                    else {
                        this.setData({
                            haveVote: 1,
                            message: "提交成功"
                        })
                    }
                    
                }
            })
        } else {
            let height;
            wx.createSelectorQuery().select('#form').boundingClientRect(res => {
                height = res.height
            }).exec()
            wx.createSelectorQuery().select('#label' + scrollTo.toString()).boundingClientRect(res => {
                wx.pageScrollTo({
                    scrollTop: height + res.top - wx.getSystemInfoSync().windowHeight, // 滚动到的位置（距离顶部 px)
                    duration: 300 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
                })
            }).exec()
            this.setData({
                itemArr: itemArr,
            })
        }
    }),

    formSubmitPage: util.throttle(function (e) {
        let Info = [];
        let score = 0;
        let itemArr = this.data.itemArr

        for (let i in itemArr) {
            if (i == "progressNum") continue;
            let vals = itemArr[i].preValue;
            console.log(itemArr[i])
            let type = itemArr[i].type;
            let title = itemArr[i].formItemProps.label;
            let answer = itemArr[i].formItemProps.answer || {}
            let preScore = 0

            if (type == "input" || type == "textarea") {
                if (vals == answer.value) {
                    preScore = answer.score
                }
                Info.push({
                    title: title,
                    content: vals,
                    score: preScore
                })
            } else if (type == "radio") {
                for (let j in answer) {
                    if (answer[j].label == vals) {
                        preScore = answer[j].score;
                        break;
                    }
                }
                Info.push({
                    title: title,
                    content: vals,
                    score: preScore
                })
            } else if (type == "checkbox") {
                let correctAnswer = []
                let correctScore = []
                for (let j in answer) {
                    if (answer[j].score != 0) {
                        correctAnswer.push(answer[j].label)
                        correctScore.push(answer[j].score)
                    }
                }
                for (let j in vals) {
                    if (correctAnswer.indexOf(vals[j]) >= 0) {
                        preScore += correctScore[correctAnswer.indexOf(vals[j])]
                    } else {
                        preScore = 0;
                        break;
                    }
                }
                Info.push({
                    title: title,
                    content: vals,
                    score: parseFloat(preScore.toFixed(1))
                })
            }
            score += preScore;
        }
        console.log("submit data", Info);
        wx.request({
            url: app.questionnaireUrl + '/recordFormal/insertOrUpdateRecord',
            method: 'POST',
            data: {
                formKey: this.data.formKey,
                data: Info,
                userId: app.globalData.userId,
                userName: app.globalData.realname,
                score: score
            },
            dataType: 'json',
            success: res => {
                wx.removeStorageSync(this.data.formKey.toString())
                this.setData({
                    success: 1,
                    message: "提交问卷成功"
                })
            }
        })
    }),
})